package com.sx.mvvmlibs.binding.edittext;

import android.content.Context;
import android.text.InputFilter;
import android.text.Spanned;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import androidx.databinding.BindingAdapter;

import java.util.ArrayList;


/**
 * @author: YY
 * @time: 2021/6/2
 * @describe 输入框 事件绑定
 */
public class viewAdapter {

    /**
     * EditText重新获取焦点的事件绑定
     */
    @BindingAdapter(value = {"requestFocus"}, requireAll = false)
    public static void requestFocusCommand(EditText editText, final Boolean needRequestFocus) {
        if (needRequestFocus) {
            editText.setSelection(editText.getText().length());
            editText.requestFocus();
            InputMethodManager imm = (InputMethodManager) editText.getContext()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
        }
        editText.setFocusableInTouchMode(needRequestFocus);
    }


    //过滤换行空格
    @BindingAdapter(value = {"editFilter"})
    public static void filterEditText(EditText editText, boolean filter) {
        if (editText != null && filter) {
            InputFilter inputFilter = new InputFilter() {
                @Override
                public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                    if (source.equals(" ") || source.toString().contentEquals("\n")) {
                        return "";
                    } else {
                        return null;
                    }
                }
            };
            InputFilter[] filters = editText.getFilters();
            ArrayList<InputFilter> inputFilters = new ArrayList<>();
            if (filters != null) {
                for (InputFilter filter1 : filters) {
                    inputFilters.add(filter1);
                }
            }
            inputFilters.add(inputFilter);
            InputFilter[] inputFilters1 = new InputFilter[inputFilters.size()];
            for (int i = 0; i < inputFilters.size(); i++) {
                inputFilters1[i] = inputFilters.get(i);
            }
            editText.setFilters(inputFilters1);
        }
    }


}
